package entity.lemming;

import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;

import entity.Entity;
import entity.terrain.Terrain;
import level.*;

/**
 * The Digger Lemming, a Lemming that digs vertically through the terrain.
 * 
 * @author Neil Cowzer, Olga Murdoch
 */
public class Digger extends Lemming {
	


	/**
	 * Create an instance of the Digger Lemming.
	 * 
	 * @param x the starting x-coordinate.
	 * @param y the starting y-coordinate.
	 */
	/*@ requires 0 <= x && 0 <= y && level != null;
		assignable speed_X && speed_Y && energy;
		ensures speed_X == 0 && speed_Y > 0 && energy == 100;
	 */
	public Digger(int x, int y){
			super("resource/graphics/lemming/digger/digger_1.gif",8, x, y);
			speed_X = 0;
			speed_Y = 1;
			energy = 45;
	}
	
	/**
	 * Create a new Digger with the given center point
	 * 
	 * @param center point of the Lemming
	 */
	public Digger(Point center){
		super("resource/graphics/lemming/digger/digger_1.gif",8, center);
		speed_X = 0;
		speed_Y = 1;
		energy = 45;
	}


	/**
	 * Checks for a collision with another Entity
	 * 
	 * @param other another Entity eg Terrain, Lemming.
	 * @return true if a collision has occured.
	 */
	public /*@ pure @*/ boolean collision(Lemming other) {
		Rectangle me = getBounds();
		if (other instanceof Blocker){
			if (me.intersects(other.getBounds())){
				return true;
			}
		}
		return false;
	}

	/** Perform the logic of moving a Lemming. */
	//@ ensures y = \old(y) + speed_Y && energy == \old(energy) -1;
	public void move(Terrain terrain) {
		boolean dig = false;
		Rectangle lemming = getBounds();
		
		if (lemming.intersects(terrain.getBounds())){
			BufferedImage image = ((Terrain)terrain).getImage().getBufferedImage();
			int black = -16777216; // black that represents the background
			int black2 = -16776960;
			try{
				// if the is at least one non- black pixel - dig
				for (int i = getX(); i < getX() + lemming.width; i++){
					int color = image.getRGB(i, y+lemming.height+1);
					
					if (color != black){
						//if(color != black2){
							dig = true;
						//}
						break;
					}
				}
				
				if (dig){
					if (energy == 45){
						for (int i = y; i < y + lemming.height; i++){
							terrain.destroyTerrain(x, i, "digger");
						}
					}
					terrain.destroyTerrain(x, y+lemming.height, "digger");
				} else {
					fall = true;
				}
			}catch(ArrayIndexOutOfBoundsException e){}
		}
		
				//update positions
		y= y+speed_Y;
		update();
		energy--;
	}
	
	/** Override turnAround. */
	public void turnAround(){
		// do nothing!
	}
}
